//
//  SearchPageViewController.m
//  MoGuRadio
//
//  Created by dlios on 15/6/3.
//  Copyright (c) 2015年 mogu.com 蘑菇科技. All rights reserved.
//

#import "SearchPageViewController.h"
#import "MyRadioViewController.h"
#import "SpecialPageViewController.h"
#import "YRSideViewController.h"
#import "AllDetail.h"

//第三方
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "UIImageView+AFNetworking.h"

//自定义cell
#import "AllPageTableViewCell.h"

// 自定义model
#import "BaseObject.h"
#import "BaseModel.h"

#define TABLEVIEW_REUSE @"MainTableViewReuseIdentifier"

@interface SearchPageViewController () <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchResultsUpdating, UISearchControllerDelegate, MBProgressHUDDelegate>
{
    MBProgressHUD *_hud;
}

@property (nonatomic, retain) NSMutableArray *searchArr;
@property (nonatomic, retain) UISearchController *searchController;
@property (nonatomic, retain) UITableView *dataTableView;

@end


@implementation SearchPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initTableView];
    [self initSearch];
    
    // 导航栏左侧按钮
    UIImage *leftButtonImage = [UIImage imageNamed:@"liftFind@2x"];
    leftButtonImage = [leftButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:leftButtonImage style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction:)] autorelease];
}



#define mark - init

- (void)initTableView
{
    _dataTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _dataTableView.delegate = self;
    _dataTableView.dataSource = self;
    _dataTableView.tableHeaderView = self.searchController.searchBar;
    [self.view addSubview:_dataTableView];
    
    [_dataTableView registerClass:[AllPageTableViewCell  class] forCellReuseIdentifier:TABLEVIEW_REUSE];
}

- (void)initSearch
{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.delegate = self;
    self.searchController.delegate = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.placeholder = @"搜索您喜欢的电台节目";
    self.searchController.searchBar.keyboardAppearance = UIKeyboardAppearanceDark;
    
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 45);
    
    _dataTableView.tableHeaderView = self.searchController.searchBar;
    
    [self.dataTableView addSubview:self.searchController.searchBar];
    // 音乐
}
                      



#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchController.active) {
        
        return self.searchArr.count;
        
    } else {
        
        return self.searchArr.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AllPageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TABLEVIEW_REUSE];
    
    AllDetail *allDetail = self.searchArr[indexPath.row];
    
    if (self.searchController.active) {
        
        if (_searchArr.count > indexPath.row) {
            
            NSString *str = allDetail.pic;
            
            NSURL *url = [NSURL URLWithString:str];
            [cell.mainImageView setImageWithURL:url];
            
            //搜索关键词截取
            NSString *rname = allDetail.rname;
            rname = [rname stringByReplacingOccurrencesOfString:@"<em>" withString:@""];
            rname = [rname stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
            NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:rname];
            
            NSRange range = [rname rangeOfString:self.searchController.searchBar.text];
            
            //        [string addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, string.length)];
            
            // 搜索关键词变色
            [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
            
            
            cell.titleLabel.attributedText = string;
            
            cell.desLabel.text = allDetail.audioDes;
            
            NSString *listenStr = allDetail.likedNum;
            
            cell.listenLabel.text = [BaseModel listenChangeStringValue:listenStr];
            
            NSString *focusStr = allDetail.followedNum;
            
            cell.focusLabel.text = [BaseModel foucsChangeStringValue:focusStr];
            
        }
        
        
    } else {
        
        
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    AllDetail *allDetail = self.searchArr[indexPath.row];
    
    SpecialPageViewController *specialVC = [[SpecialPageViewController alloc] init];
    
    specialVC.rid = allDetail.rid;
    
    specialVC.pic = allDetail.pic;
    
    specialVC.hostName = allDetail.name;
    
    specialVC.foucsNum = allDetail.followedNum;
    
    specialVC.listenNum = allDetail.listenNum;
    
    specialVC.descRadio = allDetail.audioDes;
    
    if ([allDetail.likedNum isEqualToString:@"null"]) {
        
        specialVC.likedNum = @"28";
        
    } else {
        
        specialVC.likedNum = allDetail.likedNum;

    }
    
    specialVC.upTime = allDetail.updateTime;
    
    allDetail.rname = [allDetail.rname stringByReplacingOccurrencesOfString:@"<em>" withString:@""];
    allDetail.rname = [allDetail.rname stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
    
    specialVC.titleLabel = allDetail.rname;
    
    [self.navigationController pushViewController:specialVC animated:YES];
}


// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return VIEW_HEIGHT / 7;
}


// 具体调用的时候使用的方法也发生了改变，这个时候使用updateSearchResultsForSearchController进行结果过滤
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
//    NSString *searchStr = self.searchController.searchBar.text;

//    [self dataHandle];
//    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchStr];
//    
//    if (self.searchArr != nil) {
//        
//        [self.searchArr removeAllObjects];
//    }
//
//    // 过滤数据
//    self.searchArr = [NSMutableArray arrayWithArray:[self.dataArr filteredArrayUsingPredicate:preicate]];
    
    //刷新表格
    [self.dataTableView reloadData];
}


- (void)MBProgressHUD
{
    //加载MBProgressHUD
    
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.delegate = self;
    _hud.color = [UIColor grayColor];
    _hud.labelText = @"搜索中...";
    _hud.dimBackground = YES;
    _hud.removeFromSuperViewOnHide = YES;
    _hud.mode = MBProgressHUDModeIndeterminate;
    
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor colorWithRed:0.88 green:0.90 blue:0.738 alpha:0.4];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.searchController.searchBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.097 green:0.6701 blue:0.4134 alpha:1.0];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    self.searchController.searchBar.hidden = YES;
    
}


- (void)leftButtonAction:(UIBarButtonItem *)barButton
{
    YRSideViewController *ZHAIRUI = (YRSideViewController *)self.view.window.rootViewController;
    [ZHAIRUI showLeftViewController:YES];
}


#pragma mark - 网络请求
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSString *dataStr = [NSString stringWithFormat:@"http://api.kaolafm.com/api/v3.4/resource/search?pagesize=20&words=%@&rtype=10000,20000&pagenum=1&operator=1&timestamp=1435669180&resolution=640*960&installid=0000SZ6c&version=3.5.1&appid=0&devicetype=1&page=200008&sign=F317B886396CA8621454351A56755FF7&sessionid=AF216C1E0E8E4207B0AE92D534DCBF5A&udid=22D16F7F86EBC08060D1A4AE78E40A34&network=1&channel=appstore", self.searchController.searchBar.text];
    
    dataStr = [dataStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", nil];
    
    [manger GET:dataStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableArray *sourceArr = [[responseObject objectForKey:@"result"] objectForKey:@"dataList"];
        
        self.searchArr = [AllDetail modelArrWithDics:sourceArr];
        
        NSLog(@"%@", self.searchArr);
        // [self initTableView];
        [self.dataTableView reloadData];
        [self MBProgressHUD];
        [_hud hide:YES];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"错误信息是==%@", error);
        
        
    }];
    
}



- (void)dataHandle
{
    NSString *dataStr = [NSString stringWithFormat:@"http://api.kaolafm.com/api/v3.4/resource/search?pagesize=20&words=%@&rtype=10000,20000&pagenum=1&operator=1&timestamp=1435669180&resolution=640*960&installid=0000SZ6c&version=3.5.1&appid=0&devicetype=1&page=200008&sign=F317B886396CA8621454351A56755FF7&sessionid=AF216C1E0E8E4207B0AE92D534DCBF5A&udid=22D16F7F86EBC08060D1A4AE78E40A34&network=1&channel=appstore", self.searchController.searchBar.text];
    
    dataStr = [dataStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", nil];
    
    [manger GET:dataStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableArray *sourceArr = [[responseObject objectForKey:@"result"] objectForKey:@"dataList"];
        
        self.searchArr = [AllDetail modelArrWithDics:sourceArr];
        
        NSLog(@"%@", self.searchArr);
        // [self initTableView];
        [self.dataTableView reloadData];
        [self MBProgressHUD];
        [_hud hide:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"错误信息是==%@", error);
        
        
    }];
}

- (void)dealloc
{
    [_searchArr release];
    [_dataTableView release];
    [super dealloc];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
